package com.tiancheng.trade.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tiancheng.trade.commom.core.data.notify.PayRefundSettleResultMsgBO;
import com.tiancheng.trade.commom.core.data.notify.PayResultMsgBO;
import com.tiancheng.trade.commom.core.data.notify.PaySettleResultMsgBO;
import com.tiancheng.trade.commom.core.enums.MessageTypeEnum;
import com.tiancheng.trade.commom.core.enums.PaymentChannelEnum;
import com.tiancheng.trade.commom.core.exception.BusinessException;
import com.tiancheng.trade.commom.core.exception.error.BusinessErrorInfoEnum;
import com.tiancheng.trade.commom.core.utils.JsonUtil;
import com.tiancheng.trade.order.bo.*;
import com.tiancheng.trade.order.bo.cmq.*;
import com.tiancheng.trade.order.bo.notify.PayResultHandlerResultBO;
import com.tiancheng.trade.order.bo.notify.PayResultOrderBO;
import com.tiancheng.trade.order.enums.*;
import com.tiancheng.trade.order.model.*;
import com.tiancheng.trade.order.service.*;
import com.tiancheng.trade.commom.core.utils.DateTimeUtil;
import com.tiancheng.trade.order.util.EnumUtil;
import com.tiancheng.trade.order.util.ObjectConvertUtil;
import com.tiancheng.trade.order.util.cmq.MessageParsing;
import com.tiancheng.trade.commom.core.data.MessageBody;
import com.tiancheng.trade.order.mq.MessageProducer;
import com.tiancheng.trade.order.util.cmq.queue.producer.VipMessageProducer;
import com.tiancheng.trade.order.vo.api.VerificationOrderVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 消息订阅处理service接口实现
 *
 * @author kellen
 * @date 2024/5/22
 */
@Slf4j
@Service
public class MessageSubscribeServiceImpl implements MessageSubscribeService {

    @Resource
    private MessageParsing messageParsing;
    @Resource
    private OrderService orderService;
    @Resource
    private MessageProducer messageProducer;
    @Resource
    private RefundOrdersDetailService refundOrdersDetailService;
    @Resource
    private RefundOrdersService refundOrdersService;
    @Resource
    private AbnormalPayOrderService abnormalPayOrderService;
    @Resource
    private CouponService couponService;
    @Resource
    private SubOrderService subOrderService;
    @Resource
    private InvoiceOrderService invoiceOrderService;
    @Resource
    private CreditOrderService creditOrderService;
    @Resource
    private BankCardService bankCardService;
    @Resource
    private QrOrderService qrOrderService;
    @Resource
    private IntOrderService intOrderService;
    @Resource
    private IntRefundService intRefundService;
    @Resource
    private VipMessageProducer vipMessageProducer;
    @Resource
    private BillService billService;

    @Override
    public void handle(String message) throws BusinessException {
        MessageBody msgBody = messageParsing.get(message);
        String messageType = msgBody.getMessageType();
        if (StringUtils.isEmpty(messageType)) {
            throw new RuntimeException("未查询到指定消息类型");
        }

        MessageTypeEnum msgType = EnumUtil.getEnumByCode(MessageTypeEnum.class, messageType);
        if (msgType == null) {
            throw new RuntimeException("未查询到指定消息类型");
        }

        switch (msgType) {
            case order_coupon:
                this.coupon(msgBody);
                break;
            case order_refund:
                this.refund(msgBody);
                break;
            case order_pay_result:
                log.info("接收到支付中心-支付结果消息回调:{}", message);
                this.payResult(msgBody);
                break;
            case order_refund_result:
                log.info("接收到支付中心-退款结果消息回调:{}", message);
                this.refundResult(msgBody);
                break;
            case order_sub_status_change:
                this.statusFlowForSubOrder(msgBody);
                break;
            case order_invoice_items:
                this.syncInvoiceItems(msgBody);
                break;
            case order_invoice_make:
                this.syncInvoiceItemsAndMake(msgBody);
                break;
            case invoice_result:
                this.invoiceResult(msgBody);
                break;
            case fund_auth_freeze:
                this.fundAuthFreeze(msgBody);
                break;
            case fund_auth_unfreeze:
                this.fundAuthUnfreeze(msgBody);
                break;
            case fund_auth_operation_cancel:
                this.fundAuthOperationCancel(msgBody);
                break;
            case qrc_pay:
                this.qrcPay(msgBody);
                break;
            case qrc_trade:
                this.qrcTrade(msgBody);
            case trade_payment_settle_result:
                // 支付结算单
                this.paymentSettleResult(msgBody);
                break;
            case trade_payment_refund_settle_result:
                // 退款结算单
                this.refundSettleResult(msgBody);
                break;
        }
    }

    @Override
    public void qrOrderClose(String message) throws BusinessException {
        MessageBody msgBody = messageParsing.get(message);
        String messageType = msgBody.getMessageType();
        if (StringUtils.isEmpty(messageType)) {
            throw new RuntimeException("未查询到指定消息类型");
        }

        MessageTypeEnum msgType = EnumUtil.getEnumByCode(MessageTypeEnum.class, messageType);
        if (msgType == null) {
            throw new RuntimeException("未查询到指定消息类型");
        }

    }

    /**
     * 二维码订单异常交易流程处理
     *
     * @param messageBody
     */
    private void qrcTrade(MessageBody messageBody) {
        QrTradeMsgBO payNotifyBO = messageParsing.getData(messageBody, QrTradeMsgBO.class);
        qrOrderService.saveQrTrade(payNotifyBO);
    }

    /**
     * 二维码订单支付结果处理
     *
     * @param messageBody
     */
    private void qrcPay(MessageBody messageBody) {
        QrPayNotifyBO payNotifyBO = messageParsing.getData(messageBody, QrPayNotifyBO.class);
        qrOrderService.savePayResult(payNotifyBO);
    }

    /**
     * 银联绑定银行卡回调
     *
     * @param paramsMap 回调参数
     */
    @Override
    public void bindingBankCardCallBack(Map<String, String> paramsMap) {
        bankCardService.openCardCallbackHandler(paramsMap);
    }


    /**
     * 处理支付结果
     *
     * @param messageBody
     * @throws BusinessException
     */
    private void payResult(MessageBody messageBody) throws BusinessException {
        log.info("支付结果处理...");
        PayResultMsgBO payNotifyBO = messageParsing.getData(messageBody, PayResultMsgBO.class);
        if (PaymentChannelEnum.PAYPAL.getCode().equals(payNotifyBO.getPaymentChannel())) {
            IntPayNotifyBO intPayNotifyBO = messageParsing.getData(messageBody, IntPayNotifyBO.class);
            this.intPayResult(intPayNotifyBO); //paypal支付结果处理
            return;
        }
        final PayResultHandlerResultBO payResultHandlerResultBO = orderService.savePayResult(payNotifyBO);
        log.info("开始推送支付结果消息:{}", JsonUtil.toJsonString(payResultHandlerResultBO));
        // 通知业务侧支付成功
        for (PayResultOrderBO order : payResultHandlerResultBO.getOrders()) {
            messageProducer.payResult(order);
        }
    }

    /**
     * 退款结果处理
     *
     * @param messageBody
     * @throws BusinessException
     */
    private void refundResult(MessageBody messageBody) throws BusinessException {
        RefundNotifyBO refundNotifyBO = messageParsing.getData(messageBody, RefundNotifyBO.class);
        if (PaymentChannelEnum.PAYPAL.getCode().equals(refundNotifyBO.getPaymentChannel())) {
            this.intRefundResult(refundNotifyBO); //paypal支付退款结果处理
            return;
        }
        if (PaymentChannelEnum.APPLE.getCode().equals(refundNotifyBO.getPaymentChannel())) {
            this.appleRefundResult(refundNotifyBO); //苹果支付退款结果处理
            return;
        }
        List<RefundOrdersDetail> refundOrdersDetails = refundOrdersService.saveRefundResult(refundNotifyBO);

        // 异步通知业务侧退款结果
        RefundResultMsgBO msgBO = ObjectConvertUtil.convert(refundNotifyBO, RefundResultMsgBO.class).get();
        msgBO.setFlowId(refundNotifyBO.getFlowId());
        msgBO.setRefundId(refundOrdersDetails.get(0).getRefundId());
        msgBO.setOrderSource(refundOrdersDetails.get(0).getOrderSource());
        msgBO.setRefundChannel(refundNotifyBO.getPaymentWay());
        Order order = orderService.get(refundOrdersDetails.get(0).getOrderId());
        if (null != order) {
            msgBO.setUid(order.getUid());
            msgBO.setClientId(order.getClientId());
        }
        messageProducer.refundResult(msgBO);

        if (null != order && order.getPayChannel().equals(PaymentChannelEnum.UMS.getCode())) {
            // 针对银联渠道，在退款时需要核销，用于轧差
            VerificationOrderVO verificationOrderVO = new VerificationOrderVO();
            verificationOrderVO.setSubOrderId(refundOrdersDetails.stream().map(RefundOrdersDetail::getSubOrderId).collect(Collectors.toList()));
            subOrderService.verification(verificationOrderVO);
        }

//
//        // 判断是否有合并支付信息，有的话查询批次信息，并推送至相关系统
//        if(order!=null && !StringUtils.isEmpty(order.getBatchId())){
//
//            messageProducer.refundResult(msgBO);
//        }

        //退款成功进行优惠券退还，整单退款或主订单下子订单全部退款时退还
        //主订单号下的订单应收金额=各子订单退款申请金额的总和则表示全额退款，可进行优惠券退还
        if ("success".equals(refundNotifyBO.getStatus())) {
            List<SubOrder> subOrderList = subOrderService.find(refundOrdersDetails.stream().map(RefundOrdersDetail::getOrderId).distinct().toArray(String[]::new));
            Set<String> orderIds = subOrderList.stream().map(SubOrder::getOrderId).collect(Collectors.toSet());
            Set<String> subOrderIds = subOrderList.stream().map(SubOrder::getSubOrderId).collect(Collectors.toSet());

            //查询退款成功子订单
            List<RefundOrdersDetail> refundOrdersDetailSucs = refundOrdersDetailService.querySuccessRefundBySubOrderIds(orderIds, subOrderIds);
            if (order.getPlatformDiscount() > 0) {
                //退款成功子订单总申请金额
                int refundSucApplyAmount = refundOrdersDetailSucs.stream().mapToInt(RefundOrdersDetail::getRefundApplyAmount).sum();
                //主订单应收金额
                int orderAmount = order.getOrderAmount();
                log.info("主订单应收金额：{},退款成功累计申请金额：{}", orderAmount, refundSucApplyAmount);
                if (refundSucApplyAmount == orderAmount) {
                    // 退还优惠券（支付成功再核销）
                    CouponMsgBO couponMsgBO = new CouponMsgBO();
                    couponMsgBO.setUid(order.getUid());
                    couponMsgBO.setOrderIds(refundOrdersDetails.stream().map(RefundOrdersDetail::getOrderId).distinct().toArray(String[]::new));
                    couponService.returnCoupon(couponMsgBO.getUid(), couponMsgBO.getOrderIds(), couponMsgBO.getSubOrderIds());

                }
            }
            //推送退款消息至会员系统
            //this.sendVipMsgRefund(order, refundOrdersDetailSucs);
        }

    }


    /**
     * 推送退款消息至会员系统
     *
     * @param order
     * @param refundOrdersDetailSucs
     */
    private void sendVipMsgRefund(Order order, List<RefundOrdersDetail> refundOrdersDetailSucs) {
        // 发送取消消息
        VipMsgBO vipMsgBO = new VipMsgBO();
        vipMsgBO.setUid(order.getUid());
        vipMsgBO.setType("consumption");
        vipMsgBO.setAction(VipMessageProducer.ACTION_REFUND);
        vipMsgBO.setScene(order.getOrderSource());
        vipMsgBO.setTime(DateTimeUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
        Map<String, Object> orderMap = new HashMap<>();
        orderMap.put("order_id", order.getOrderId());
        orderMap.put("refund_id", refundOrdersDetailSucs.get(0).getRefundId());
        final List<Map<String, Object>> subOrders = new ArrayList<>(refundOrdersDetailSucs.size());
        for (RefundOrdersDetail refundOrdersDetailSuc : refundOrdersDetailSucs) {
            Map<String, Object> s = new HashMap<>();
            s.put("sub_order_id", refundOrdersDetailSuc.getSubOrderId());
            s.put("amount", refundOrdersDetailSuc.getRefundAmount());
            subOrders.add(s);
        }
        orderMap.put("list", subOrders);
        vipMsgBO.setExtend(orderMap);
        log.info("订单退款成功，释放锁定的会员权益:{}", JsonUtil.toJsonString(vipMsgBO));
        final boolean sec = vipMessageProducer.sendVipMsg(vipMsgBO);
        if (!sec) {
            vipMessageProducer.sendVipMsg(vipMsgBO);
        }
    }

    /**
     * 苹果支付结果处理
     *
     * @param refundNotifyBO 支付回调消息
     */
    private void appleRefundResult(RefundNotifyBO refundNotifyBO) {
        List<RefundOrdersDetail> refundOrdersDetails = refundOrdersDetailService.saveApplePayResult(refundNotifyBO);
        log.info("苹果支付，开始推送退款结果消息:{}", JsonUtil.toJsonString(refundNotifyBO));
        // 异步通知业务侧退款结果
        AppleRefundResultMsgBO msgBO = ObjectConvertUtil.convert(refundNotifyBO, AppleRefundResultMsgBO.class).get();
        msgBO.setOrderSource(refundOrdersDetails.get(0).getOrderSource());
        msgBO.setRefundChannel(refundNotifyBO.getPaymentWay());
        msgBO.setOrderId(refundOrdersDetails.get(0).getOrderId());
        Order order = orderService.get(refundOrdersDetails.get(0).getOrderId());
        if (null != order) {
            msgBO.setUid(order.getUid());
        }
        messageProducer.appleRefundResult(msgBO);
    }

    /**
     * 推送支付消息至会员系统
     *
     * @param orders
     * @param subOrders
     */
    private void sendVipMsgPay(List<Order> orders, List<SubOrder> subOrders) {
        for (Order order : orders) {
            // 发送取消消息
            VipMsgBO vipMsgBO = new VipMsgBO();
            vipMsgBO.setUid(order.getUid());
            vipMsgBO.setType("consumption");
            vipMsgBO.setAction(VipMessageProducer.ACTION_PAY);
            vipMsgBO.setScene(order.getOrderSource());
            vipMsgBO.setTime(DateTimeUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"));
            Map<String, Object> orderMap = new HashMap<>();
            orderMap.put("order_id", order.getOrderId());
            final List<Map<String, Object>> sos = new ArrayList<>();
            subOrders.stream().filter(s -> s.getOrderId().equals(order.getOrderId())).forEach(s -> {
                Map<String, Object> subOrder = new HashMap<>();
                subOrder.put("sub_order_id", s.getSubOrderId());
                subOrder.put("amount", s.getPayAmount());
                sos.add(subOrder);
            });

            orderMap.put("list", sos);
            vipMsgBO.setExtend(orderMap);
            log.info("支付订单，推送会员权益:{}", JsonUtil.toJsonString(vipMsgBO));
            final boolean sec = vipMessageProducer.sendVipMsg(vipMsgBO);
            if (!sec) {
                vipMessageProducer.sendVipMsg(vipMsgBO);
            }
        }
    }

    /**
     * 异常退款
     *
     * @param messageBody
     * @throws BusinessException
     */
    private void refund(MessageBody messageBody) throws BusinessException {
        RefundMsgBO refundMsgBO = messageParsing.getData(messageBody, RefundMsgBO.class);

        BusinessErrorInfoEnum.ORDER_REFUND_NO_DATA.assertIsTrue(refundMsgBO.getOrderIds().length > 0);

        // 暂时先记录重复支付的订单信息
        AbnormalPayOrderBO abnormalPayOrderBO = new AbnormalPayOrderBO();
        abnormalPayOrderBO.setUid(refundMsgBO.getUserId());
        abnormalPayOrderBO.setFlowId(refundMsgBO.getPayFlowId());
        abnormalPayOrderBO.setPaymentId(refundMsgBO.getPaymentId());
        abnormalPayOrderBO.setPayTime(refundMsgBO.getPayTime());
        abnormalPayOrderBO.setOrderIds(refundMsgBO.getOrderIds());
        abnormalPayOrderService.save(abnormalPayOrderBO);

        // todo 重复退款的逻辑待定，因为重复支付退款后，重叠的子订单，有效支付有可能退款不了
//			List<Refund> refunds = refundService.getRefundForRepeatPay(refundMsgBO.getUserId(), refundMsgBO);
//			refundService.saveRefundForRepeatPay(refunds, refundMsgBO);
//			// 发起退款
//			refundService.refundForRepeatPay(refunds, refundMsgBO);
    }

    /**
     * 核销、释放优惠券
     *
     * @param messageBody
     * @throws BusinessException
     */
    private void coupon(MessageBody messageBody) throws BusinessException {
        CouponMsgBO couponMsgBO = messageParsing.getData(messageBody, CouponMsgBO.class);

        if (couponMsgBO.getStatus().equals(CouponStatusEnum.verification.getCode())) {
            couponService.writeOff(couponMsgBO.getUid(), couponMsgBO.getOrderIds(), couponMsgBO.getSubOrderIds());
        } else if (couponMsgBO.getStatus().equals(CouponStatusEnum.bind.getCode())) {
            couponService.unlock(couponMsgBO.getUid(), couponMsgBO.getOrderIds(), couponMsgBO.getSubOrderIds());
        }
    }

    /**
     * 子订单状态流转，mq传入
     *
     * @param messageBody
     * @throws BusinessException
     */
    private void statusFlowForSubOrder(MessageBody messageBody) throws BusinessException {
        Map<String, Object> bodyMap = messageParsing.getData(messageBody, Map.class);
        String orderId = String.valueOf(bodyMap.get("order_id"));
        String bizStatus = String.valueOf(bodyMap.get("biz_status"));
        List<String> subOrderIdList = null;
        if (bodyMap.containsKey("sub_order_id")) {
            subOrderIdList = (List<String>) bodyMap.get("sub_order_id");
        }
        this.statusFlowForSubOrderByInterface(orderId, bizStatus, subOrderIdList);
    }

    /**
     * 子订单状态流转,接口传入
     *
     * @param orderId
     * @param bizStatus
     * @param subOrderIdList
     * @throws BusinessException
     */
    @Override
    public void statusFlowForSubOrderByInterface(String orderId, String bizStatus, List<String> subOrderIdList) throws BusinessException {
        String[] subOrderIds = null;
        if (!CollectionUtils.isEmpty(subOrderIdList)) {
            subOrderIdList = subOrderIdList.stream().filter(s -> !StringUtils.isEmpty(s) && !s.equalsIgnoreCase("null")).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(subOrderIdList)) {
                subOrderIds = subOrderIdList.toArray(new String[subOrderIdList.size()]);
            }
        }
        messageProducer.orderStateChangeMessage(new OrderStateChangeMsgBo(orderId, subOrderIds, bizStatus));
    }


    /**
     * 业务侧（诚选、包租车等）将订单可开票明细同步
     *
     * @param messageBody
     */
    private void syncInvoiceItems(MessageBody messageBody) {
        InvoiceOrderBO invoiceOrderBO = messageParsing.getData(messageBody, InvoiceOrderBO.class);
        if (!StringUtils.isEmpty(invoiceOrderBO.getItems())) {
            invoiceOrderBO.setItems(StringEscapeUtils.unescapeJava(invoiceOrderBO.getItems()));
        }
        invoiceOrderService.syncInvoiceItems(invoiceOrderBO);
    }

    /**
     * 业务侧，将订单可开票明细同步，并直接开具发票
     *
     * @param messageBody
     */
    private void syncInvoiceItemsAndMake(MessageBody messageBody) {
        InvoiceOrderBO invoiceOrderBO = messageParsing.getData(messageBody, InvoiceOrderBO.class);
        if (!StringUtils.isEmpty(invoiceOrderBO.getItems())) {
            invoiceOrderBO.setItems(StringEscapeUtils.unescapeJava(invoiceOrderBO.getItems()));
        }
        invoiceOrderService.syncInvoiceItemsAndMake(invoiceOrderBO);
    }

    /**
     * 开票结果通知
     *
     * @param messageBody
     */
    private void invoiceResult(MessageBody messageBody) {
        InvoiceResultBO invoiceResultBO = messageParsing.getData(messageBody, InvoiceResultBO.class);
        invoiceOrderService.invoiceResult(invoiceResultBO);
    }


    /**
     * 信用订单预授权冻结-结果通知
     *
     * @param messageBody
     */
    public void fundAuthFreeze(MessageBody messageBody) {
        log.info("信用订单预授权冻结回调:{}", JsonUtil.toJsonString(messageBody));
        CreditOrderFundAuthFreezeBo freezeBo = JSON.parseObject(JSON.toJSONString(messageBody.getData()), CreditOrderFundAuthFreezeBo.class);
        // 更新冻结运单信息
        CreditOrder creditOrder = creditOrderService.updateFundAuthFreeze(freezeBo);
        if (null != creditOrder) {
            messageProducer.tallyBizCreditOrder(creditOrder2CreditOrderBO(creditOrder), CreditOrderMsgTagEnum.FUND_AUTH_FREEZE);
        }

    }

    /**
     * 信用订单预授权解冻-结果通知
     *
     * @param messageBody
     */
    public void fundAuthUnfreeze(MessageBody messageBody) {
        log.info("信用订单预授权解冻回调:{}", JsonUtil.toJsonString(messageBody));

        Map<String, Object> bodyMap = messageParsing.getData(messageBody, Map.class);
        String gwOrderId = String.valueOf(bodyMap.get("gwOrderId"));
        String requestNo = String.valueOf(bodyMap.get("requestNo"));
        CreditOrder creditOrder = creditOrderService.fundAuthUnfreeze(gwOrderId, requestNo);
        if (null != creditOrder) {
            messageProducer.tallyBizCreditOrder(creditOrder2CreditOrderBO(creditOrder), CreditOrderMsgTagEnum.ALIPAY_CREDIT_ORDER_FINISHED);
        }
    }

    /**
     * 信用订单预授权操作取消-结果通知
     *
     * @param messageBody
     */
    public void fundAuthOperationCancel(MessageBody messageBody) {
        log.info("信用订单预授权操作取消回调:{}", JsonUtil.toJsonString(messageBody));
        Map<String, Object> bodyMap = messageParsing.getData(messageBody, Map.class);
        String gwOrderId = String.valueOf(bodyMap.get("gwOrderId"));
        String requestNo = String.valueOf(bodyMap.get("requestNo"));
        CreditOrder creditOrder = creditOrderService.cancelConfirm(gwOrderId, requestNo);
        if (null != creditOrder) {
            messageProducer.tallyBizCreditOrder(creditOrder2CreditOrderBO(creditOrder), CreditOrderMsgTagEnum.FUND_AUTH_OPERATION_CANCEL);
        }

    }

    /**
     * 预授权转支付通知回调
     * 信用订单授权转支付-结果通知
     *
     * @param messageBody
     */
    public void fundAuthTradeStatusSync(MessageBody messageBody) {
        //paidConfirm
        log.info("预授权转支付通知回调:{}", JsonUtil.toJsonString(messageBody));
        Map<String, Object> bodyMap = messageParsing.getData(messageBody, Map.class);
        String gwOrderId = String.valueOf(bodyMap.get("gwOrderId"));
        CreditOrder creditOrder = creditOrderService.tradeStatusSync(gwOrderId);
        if (null != creditOrder) {
            messageProducer.tallyBizCreditOrder(creditOrder2CreditOrderBO(creditOrder), CreditOrderMsgTagEnum.FUND_AUTH_OPERATION_CANCEL);
        }

    }

    private CreditOrderBO creditOrder2CreditOrderBO(CreditOrder creditOrder) {
        Optional<CreditOrderBO> convert = ObjectConvertUtil.convert(creditOrder, CreditOrderBO.class);
        return convert.orElse(null);
    }


    private boolean isOldOrderZhiMaMsg(MessageBody messageBody) {
        Map<String, Object> bodyMap = messageParsing.getData(messageBody, Map.class);
        return bodyMap.containsKey("gwOrderId") && !Objects.nonNull(bodyMap.get("gwOrderId")) && bodyMap.get("gwOrderId").toString().length() <= 18;
    }


    /**
     * 处理paypal支付结果
     *
     * @param intPayNotifyBO
     * @throws BusinessException
     */
    public void intPayResult(IntPayNotifyBO intPayNotifyBO) throws BusinessException {
        intOrderService.intPayResult(intPayNotifyBO);
      /*  //IntPayNotifyBO intPayNotifyBO = messageParsing.getData(messageBody, IntPayNotifyBO.class);
        intOrderService.savePayResult(intPayNotifyBO);
        log.info("开始推送支付结果消息:{}", JsonUtil.toJsonString(intPayNotifyBO));
        String uid=intPayNotifyBO.getUserId();

        // 通知业务侧支付成功
        List<IntOrder> orders = intOrderService.findByOrderIds(intPayNotifyBO.getOrders().stream().
                map(IntOrder::getOrderId).collect(Collectors.toSet()));
        intPayNotifyBO.setOrders(orders);
        for (IntOrder intOrder : orders) {
            PayResultMsgBO payResultMsgBO = new PayResultMsgBO();
            payResultMsgBO.setOrderId(intOrder.getOrderId());
            payResultMsgBO.setAmount(intOrder.getPayAmount());
            payResultMsgBO.setOrderSource(intOrder.getOrderSource());
            payResultMsgBO.setUserId(intOrder.getUid());
            payResultMsgBO.setStatus(intPayNotifyBO.getStatus());
            payResultMsgBO.setPayTime(intPayNotifyBO.getPayTime());
            payResultMsgBO.setChannelOrderid(intPayNotifyBO.getTradeNo());
            payResultMsgBO.setPayChannelOrderid(intPayNotifyBO.getTradeNo());
            payResultMsgBO.setPayChannel(intOrder.getPayWay());
            payResultMsgBO.setSystemSource(intOrder.getSystemSource());
            payResultMsgBO.setPayScene(intOrder.getPayScene());
            payResultMsgBO.setCouponAmount(intOrder.getDiscount());
            messageProducer.payResult(payResultMsgBO);
        }*/
    }


    /**
     * 处理paypal支付退款结果
     *
     * @param refundNotifyBO
     * @throws BusinessException
     */
    public void intRefundResult(RefundNotifyBO refundNotifyBO) throws BusinessException {
        List<IntRefund> intRefunds = intRefundService.saveRefundResult(refundNotifyBO);
        log.info("开始推送退款结果消息:{}", JsonUtil.toJsonString(refundNotifyBO));
        // 异步通知业务侧退款结果
        RefundResultMsgBO msgBO = ObjectConvertUtil.convert(refundNotifyBO, RefundResultMsgBO.class).get();
        msgBO.setOrderSource(intRefunds.get(0).getOrderSource());
        msgBO.setRefundChannel(refundNotifyBO.getPaymentWay());
        IntOrder intOrder = intOrderService.get(intRefunds.get(0).getOrderId());
        if (null != intOrder) {
            //msgBO.setSystemSource(intOrder.getSystemSource());
            msgBO.setUid(intOrder.getUid());
        }
        messageProducer.refundResult(msgBO);
    }

    /**
     * 支付结算结果处理
     *
     * @param msgBody
     */
    private void paymentSettleResult(MessageBody msgBody) {
        log.info("支付订单结算完成通知回调:{}", JsonUtil.toJsonString(msgBody));
        PaySettleResultMsgBO paySettleResultMsgBO = messageParsing.getData(msgBody, PaySettleResultMsgBO.class);
        billService.paymentSettleResult(paySettleResultMsgBO);
    }

    /**
     * 退款结算结果处理
     *
     * @param msgBody
     */
    private void refundSettleResult(MessageBody msgBody) {
        log.info("退款结算单结算完成通知回调:{}", JsonUtil.toJsonString(msgBody));
        PayRefundSettleResultMsgBO refundSettleResultMsgBO = messageParsing.getData(msgBody, PayRefundSettleResultMsgBO.class);
        billService.refundSettleResult(refundSettleResultMsgBO);
    }
}
